<template>
  <div class="app-container">
    <br>
    <div class="div1">
      <label>原始数据</label>
      <el-table
        ref="tableList"
        :data="crawlerObj"
        border
        stripe
        :header-cell-style="headStyle"
        :cell-style="cellStyle"
      >

        <el-table-column prop="dataId" label="数据ID" width="120" />
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="location" label="来源地区" width="100" />
        <el-table-column prop="author" label="来源" width="200" :show-overflow-tooltip="true" />
        <el-table-column prop="cateId" label="分类ID" width="100">
          <template slot-scope="scope">
            <span v-if="scope.row.cateId == 1">招标</span>
            <span v-else-if="scope.row.cateId == 2">中标</span>
            <span v-else-if="scope.row.cateId == 3">开标</span>
            <span v-else>其他</span>
          </template>
        </el-table-column>
        <el-table-column prop="pubtime" label="发布时间" width="165" />
        <el-table-column prop="addTime" label="入库时间" width="180" />
        <el-table-column label="正文" width="100">
          <el-button type="info" size="mini" @click="previewHtml">
            预览
          </el-button>
        </el-table-column>
        <el-table-column prop="intro" label="附件" width="100">
          <template slot-scope="scope">
            <el-button type="info" size="mini" @click="downloadFile(scope.row.intro)">
              下载
            </el-button>
          </template>
        </el-table-column>
        <el-table-column prop="outurl" label="链接" width="100">
          <template slot-scope="scope">
            <el-button type="info" size="mini">
              <a :href="scope.row.outurl" target="_blank">跳转</a>
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="100">
          <el-button type="info" size="mini" @click="updateStatus(2)">
            忽略
          </el-button>
        </el-table-column>
      </el-table>
    </div>

    <div class="div2">
      <label>错误原因: </label>
      <span style="color: red">{{ reason }}</span>
    </div>
    <br>
    <label style="padding: 10px">修改数据</label>
    <div class="div3">
      <el-form ref="formData" :model="updateObj[0]" :rules="rules">
        <el-table
          ref="tableList2"
          :data="updateObj"
          border
          stripe
          :header-cell-style="headStyle"
          :cell-style="cellStyle"
        >
          <el-table-column prop="dataId" label="数据ID" width="120" />
          <el-table-column prop="title" label="标题" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-form-item prop="title">
                <el-input v-model="scope.row.title" name="title" @blur="handleBlur('title')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="location" label="来源地区" width="100">
            <template slot-scope="scope">
              <el-form-item prop="location">
                <el-input v-model="scope.row.location" name="location" @blur="handleBlur('location')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="author" label="来源" width="200">
            <template slot-scope="scope">
              <el-form-item prop="author">
                <el-input v-model="scope.row.author" name="author" @blur="handleBlur('author')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="cateId" label="分类ID" width="100">
            <template slot-scope="scope">
              <el-form-item prop="cateId">
                <el-select v-model="scope.row.cateId" @blur="handleBlur('cateId')">
                  <el-option
                    v-for="item in cateIds"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="pubtime" label="发布时间" width="165">
            <template slot-scope="scope">
              <el-form-item prop="pubtime">
                <el-date-picker
                  v-model="scope.row.pubtime"
                  type="date"
                  style="width: 140px"
                  value-format="yyyy-MM-dd"
                  :clearable="false"
                  @blur="handleBlur('pubtime')"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="addTime" label="入库时间" width="180" />
          <el-table-column label="正文" width="100">
            <el-button type="info" size="mini" @click="dialogInfoVisible = true">
              修改
            </el-button>
          </el-table-column>
          <el-table-column prop="intro" label="附件" width="100">
            <!--            <el-button type="info" size="mini" @click="dialogIntroVisible = true">-->
            <!--              修改-->
            <!--            </el-button>-->
            <input ref="fileInput" type="file" multiple style="display: none" @change="handleFileChanged">
            <el-button type="info" size="mini" @click="chooseFile">上传</el-button>
          </el-table-column>
          <el-table-column prop="outurl" label="链接" width="100">
            <el-button type="info" size="mini" @click="dialogUrlVisible = true">
              修改
            </el-button>
          </el-table-column>
          <el-table-column label="操作" width="100">
            <el-button type="info" size="mini" @click="updateCommit">
              保存
            </el-button>
          </el-table-column>
        </el-table>

        <el-dialog
          title="输入数据正文内容"
          :visible.sync="dialogInfoVisible"
          append-to-body
        >
          <textarea
            v-model="formData.info"
            style="height: 500px;width: 900px;"
          />
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogInfoVisible = false">取 消</el-button>
            <el-button
              type="primary"
              @click="updateInfo"
            >确 定</el-button>
          </span>
        </el-dialog>

        <el-dialog
          title="输入文件下载链接"
          :visible.sync="dialogIntroVisible"
        >
          <el-input
            v-model="formData.intro"
            style="width: 900px;"
          />
          <span slot="footer" class="dialog-footer">
            <el-button @click="dialogIntroVisible = false">取 消</el-button>
            <el-button
              type="primary"
              @click="dialogIntroVisible = false"
            >确 定</el-button>
          </span>
        </el-dialog>

        <el-dialog
          title="输入数据访问链接"
          :visible.sync="dialogUrlVisible"
          :close-on-click-modal="false"
          append-to-body
        >
          <el-form-item prop="outurl">
            <el-input
              v-model="formData.outurl"
              style="width: 900px;"
            />
          </el-form-item>
          <span slot="footer" class="dialog-footer">
            <el-button @click="cancelEditHtml">取 消</el-button>
            <el-button
              type="primary"
              @click="closeEditHtml('outurl')"
            >确 定</el-button>
          </span>
        </el-dialog>
      </el-form>
    </div>
  </div>
</template>

<script>
/* eslint-disable */
import crawlerDetailApi from '@/api/crawler/crawlerDetail'
import { MessageBox } from 'element-ui'
export default {
  name: 'Fix',
  props: {
    foridProp: 0,
    didProp: 0,
    dataIdProp: 0,
    tableNameProp: '',
    reasonProp: ''
  },

  data() {
    return {
      forid: 0, // 爬虫id
      did: 0, // 当前错误数据的id
      dataId: 0, // 当前错误数据对应的真实数据id
      tableName: '', // 表名
      reason: '',
      crawlerObj: [], // 原始数据
      updateObj: [], // 用于展示修改数据
      formData: {}, // 用于提交表单
      file: null, // 附件
      cateIds: [
        {
          value: 1,
          label: '招标'
        },
        {
          value: 2,
          label: '中标'
        },
        {
          value: 3,
          label: '开标'
        },
        {
          value: 4,
          label: '其他'
        }
      ],
      dialogInfoVisible: false, // 修改正文弹窗
      dialogIntroVisible: false, // 修改附件弹窗
      dialogUrlVisible: false, // 修改链接弹窗

      rules: {
        title: {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        },
        location: {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        },
        author: {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        },
        cateId: {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        },
        pubtime: {
          required: true,
          message: '不能为空',
          trigger: 'blur'
        },
        outurl: {
          required: true,
          message: '不能为空',
          trigger: 'change'
        }
      }

    }
  },

  mounted() {
    this.forid = this.foridProp
    this.did = this.didProp
    this.dataId = this.dataIdProp
    this.tableName = this.tableNameProp
    this.reason = this.reasonProp
    this.fetchDataById()
  },

  watch: {
    foridProp: function (newVal, oldVal) {
      this.forid = newVal
    },

    didProp: function (newVal, oldVal) {
      this.did = newVal
    },

    tableNameProp: function (newVal, oldVal) {
      this.tableName = newVal
    },

    reasonProp: function (newVal, oldVal) {
      this.reason = newVal
    },

    dataIdProp: function (newVal, oldVal) {
      this.dataId = newVal
      this.fetchDataById()
    },
  },

  methods: {
    fetchDataById() {
      const searchObj = {
        did: this.did,
        dataId: this.dataId,
        tableName: this.tableName
      }
      crawlerDetailApi.crawlerDataById(searchObj).then((response) => {
        console.log('原始 -> ', response.data.result)
        this.crawlerObj = JSON.parse(JSON.stringify(response.data.result)) // 使用JSON将返回的内容复制成两份来使用
        this.updateObj = JSON.parse(JSON.stringify(response.data.result))
        this.updateObj[0].tableName = this.tableName
        this.updateObj[0].did = this.did
        this.formData = this.updateObj[0]
        console.log('log', this.updateObj[0])
        console.log('crawler  ->', this.crawlerObj[0].info)
      })
    },

    // 预览正文弹窗
    previewHtml() {
      if (this.crawlerObj[0].info === '') {
        this.$message({
          message: 'info为空',
          type: 'warning'
        })
      } else {
        MessageBox.alert(this.crawlerObj[0].info, '预览', {
          dangerouslyUseHTMLString: true, // 允许html文本
          closeOnClickModal: true, // 允许点击空白处关闭弹窗
          customClass: 'custom-box' // css样式
        })
      }
    },

    // 外部链接取消按钮
    cancelEditHtml() {
      this.dialogUrlVisible = false
      setTimeout(() => {
        this.formData.outurl = this.crawlerObj[0].outurl
      }, 500)
    },

    // 关闭弹窗
    closeEditHtml(name) {
      this.$nextTick(() => {
        // 校验单个字段，调用validateField方法，单个参数就是校验某个字段，多个参数时，第二个参数无内容表示校验通过
        this.$refs.formData.validateField(name, (err) => {
          if (!err) {
            this.dialogInfoVisible = false
            this.dialogIntroVisible = false
            this.dialogUrlVisible = false
          }
        })
      })
      // this.$message({ message: '取消修改', type: 'info' })
    },

    // 提交修改
    updateCommit() {
      this.$refs.formData.validate((err) => {
        // true表示校验通过，false表示校验失败，validate方法是整个表单所有字段都校验
        if (!err) {
          this.$message({
            message: '内容校验不通过',
            type: 'error'
          })
        } else {
          this.$confirm('确定保存?', '提示', {
            cancelButtonText: '取消',
            confirmButtonText: '确定',
            type: 'warning'
          }).then(() => {
            return crawlerDetailApi.updateCommit(this.formData)
          }).then(() => {
            this.fetchDataById() // 刷新列表
            this.$message({
              type: 'success',
              message: '保存成功'
            })
            this.$emit('closeFix') // 向父组件传递关闭弹窗的动作
          }).catch((reason) => {
            if (reason === 'cancel') {
              this.$message({
                type: 'info',
                message: '已取消保存'
              })
            }
          })
        }
      })
    },

    // 忽略数据
    updateStatus(status) {
      crawlerDetailApi.updateStatus(status, this.did).then((response) => {
        if (response.code === 200) {
          this.$message({
            message: '忽略成功',
            type: 'success'
          })
          this.$emit('closeFix') // 向父组件传递关闭弹窗的动作
        } else {
          this.$message({
            message: response.message,
            type: 'error'
          })
        }
      })
    },

    // 更新正文
    updateInfo() {
      const infoData = new FormData()
      infoData.append('dataId', this.dataId)
      infoData.append('info', this.formData.info)
      infoData.append('tableName', this.tableName)
      crawlerDetailApi.updateInfo(infoData).then((response) => {
        if (response.code === 200) {
          this.$message({
            message: '更新成功，请预览后保存',
            type: 'success'
          })
        } else {
          this.$message({
            message: response.message,
            type: 'error'
          })
        }
      })
      this.dialogInfoVisible = false
      this.fetchDataById()
      console.log('formData ->', this.formData.info)
      console.log('crawler  ->', this.crawlerObj[0].info)
    },

    // 附件下载
    downloadFile(url) {
      if (url) {
        window.open(url)
      } else {
        this.$message({
          message: '附件为空',
          type: 'warning'
        })
      }
    },

    // 附件上传
    chooseFile() {
      // 触发隐藏的文件选择框
      this.$refs.fileInput.click()
    },

    handleFileChanged() {
      const file = this.$refs.fileInput.files[0]
      const formData = new FormData()
      formData.append('file', file)
      formData.append('id', this.dataId)
      formData.append('tableName', this.tableName)
      crawlerDetailApi.uploadFile(formData).then((response) => {
        this.$message({
          message: response.message,
          type: 'success'
        })
        this.$refs.fileInput.value = ''
      }).catch((err) => {
        this.$refs.fileInput.value = ''
      })
    },

    handleBlur(name) {
      this.$nextTick(() => {
        // 校验单个字段，调用validateField方法，单个参数就是校验某个字段，多个参数时，第二个参数无内容表示校验通过
        this.$refs.formData.validateField(name)
      })
    },

    back() {
      // this.$router.push({ path: '/crawler/detail/' + this.id })
      this.$router.go(-1)
    },

    // 表头style
    headStyle() {
      return 'text-align: center; font-size: 16px; height: 90px; color: black; backgroundColor: rgba(160,188,231,0.1)'
    },

    // 列style
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if ((rowIndex + 1) % 2 === 0) {
        return 'text-align: center; font-size: 15px; height: 60px; color: #303133; background: rgba(160,188,231,0.1)'
      } else {
        return 'text-align: center; font-size: 15px; height: 60px; color: #303133; backgroundColor: white'
      }
    }
  }
}
</script>

<style scoped>
  .div1 {
    padding: 10px;
  }
  .div2 {
    padding: 20px 10px 20px;
  }
  .div3 {
    padding: 10px;
  }
</style>
<style>
  .custom-box {
    height: 900px;
    width: 1000px;
    overflow-y: auto;
  }
</style>
